<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学校名称" prop="sname">
        <el-input
          v-model="queryParams.sname"
          placeholder="请输入学校名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校代码" prop="scode">
        <el-input
          v-model="queryParams.scode"
          placeholder="请输入学校代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="院校排名" prop="sranking">
        <el-input
          v-model="queryParams.sranking"
          placeholder="请输入院校排名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['school:school:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['school:school:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['school:school:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['school:school:export']"
        >导出</el-button>
      </el-col>



    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="#" type="index" width="50" align="center">-->
<!--            <template scope="scope">-->
<!--          <span>{{-->
<!--            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1-->
<!--          }}</span>-->
<!--            </template>-->
<!--        </el-table-column>-->
      <el-table-column  label="学校id" align="center" prop="sid" />
      <el-table-column
        label="学校logo"
        align="center"
        prop="slogo"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.slogo"
          :src="scope.row.slogo"
          :width="50"
          :height="50"
          />
          <!-- 你可以在这里加入一个占位符或者提示信息，当图片不存在时显示 -->
          <div v-else>暂无logo</div>
        </template>
      </el-table-column>
      <el-table-column label="学校名称" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.sname }}</div>
          <div style="color: red;">{{ getSchoolTypeLevel(scope.row.collegeLevel) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="学校类型" align="center">
        <template slot-scope="scope">
          {{ getSchoolTypeLabel(scope.row.stypes) }}
        </template>
      </el-table-column>
      <el-table-column label="学校代码" align="center" prop="scode" />
      <el-table-column label="学校省份" align="center" prop="schoolAreadto.provinceName" />
      <el-table-column label="学校城市" align="center" prop="schoolAreadto.cityName" />

      <el-table-column label="院校排名" align="center" prop="sranking" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['school:school:edit']"
          >修改</el-button>


<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleIntroduce(scope.row),centerDialogVisible=true"-->
<!--          >学校简介</el-button>-->


          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['school:school:remove']"
          >删除</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="form-item-row">
<!--          <el-form-item label="学校省份" prop="sprovince">-->
<!--            <el-input v-model="form.sprovince" placeholder="请输入学校省份" />-->
<!--          </el-form-item>-->

<!--          <el-form-item label="学校省份" @click.native="selectArea" prop="sprovince">-->

<!--          </el-form-item>-->

<!--          <el-button type="text" @click="selectArea">查看设置</el-button>-->


          <el-form-item label="学校省份">
            <el-select v-model="form.sprovince" placeholder="请选择省份" @change="handleProvinceChange">
              <el-option
                v-for="item in AreaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="学校类型" prop="stypes">
            <el-select v-model="form.stypes" placeholder="请选择学校类型" style="width: 100%">
              <el-option
                v-for="dict in dict.type.school_types"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"            ></el-option>
            </el-select>
          </el-form-item>

          </div>
        <div class="form-item-row">
          <el-form-item label="重点院校">
            <el-checkbox-group v-model="form.collegeLevel">
              <el-checkbox
                v-for="dict in dict.type.school_level"
                :key="dict.value"
                :label="dict.value">
                {{dict.label}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
<!--          <el-form-item label="录取批次" prop="sbatch">-->
<!--            <el-input v-model="form.sbatch" placeholder="请输入录取批次" />-->
<!--          </el-form-item>-->
        </div>
        <div class="form-item-row">
          <el-form-item label="学校城市">
            <el-select v-model="form.city" placeholder="请选择城市">
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>



          <el-form-item label="学校名称" prop="sname">
            <el-input v-model="form.sname" placeholder="请输入学校名称" />
          </el-form-item>
        </div>
        <div class="form-item-row">
          <el-form-item label="学校代码" prop="scode">
            <el-input v-model="form.scode" placeholder="请输入学校代码" />
          </el-form-item>
          <el-form-item label="院校排名" prop="sranking">
            <el-input v-model="form.sranking" placeholder="请输入院校排名" />
          </el-form-item>
        </div>
        <div class="form-item-row">

          <el-form-item label="官方网址" prop="swebsite">
            <el-input v-model="form.swebsite" placeholder="请输入学校网址" />
          </el-form-item>

          <el-form-item label="招生网址" prop="">
            <el-input v-model="form.recruitWeb" placeholder="请输入招生网址" />
          </el-form-item>
<!--          <el-form-item label="办学方式" prop="smodel">-->
<!--            <el-input v-model="form.smodel" placeholder="请输入办学方式" />-->
<!--          </el-form-item>-->
        </div>
		<div class="form-item-row">
		  <el-form-item label="招生章程" prop="">
		    <el-input v-model="form.zszc" placeholder="请输入招生章程网址" />
		  </el-form-item>
		  </div>
        <div class="form-item-row">
          <el-form-item label="主管部门" prop="">
            <el-input v-model="form.sdepartment" placeholder="请输入主管部门" />
          </el-form-item>
          <el-form-item label="官方电话" prop="">
            <el-input v-model="form.smodel" placeholder="请输入官方电话" />
          </el-form-item>
          </div>
        <div class="form-item-row">
          <el-form-item label="学校logo" prop="slogo">
            <image-upload v-model="form.slogo" :limit="1" />
          </el-form-item>
        </div>

        <div class="form-item-row">
          <el-form-item label="学校简介" style="width: 100%;">
            <editor v-model="form.scontent" :min-height="100"/>
          </el-form-item>
        </div>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
		
		<el-form-item label="专业录取规则" prop="admssionRule">
		  <el-input v-model="form.admssionRule" type="textarea" placeholder="请输入内容" />
		</el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

<!-- 学校简介弹出框 -->
    <el-dialog
      title="学校简介"
      :visible.sync="centerDialogVisible"
      width="50%"
      center>
      <span v-html="form.scontent"></span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>




  </div>
</template>

<script>
import { listSchool,
  getSchool, delSchool,
  addSchool, updateSchool
  ,listArea,getSchoolIntroduce,
  basearea,getCity

} from "@/api/school/school";
import treeTransfer from 'el-tree-transfer'



export default {
  name: "School",
  dicts: ['school_level',"school_types"],

  components: {
    treeTransfer,
  },

  data() {
    return {

      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //学校介绍弹出框
      centerDialogVisible: false,

      innerVisible:false,

      addArea: [],

      removeArea: [],

      areaData: [],

      selectAreaData: [],

      mode: 'transfer',

      // 总条数
      total: 0,
      // 学校列表表格数据
      schoolList: [],

      AreaList: [],//省份列表

      cityOptions: [],//城市列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "s_code",
        isAsc: "",
        sname: null,
        scode: null,
        sranking: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sname: [
          { required: true, message: "学校名称不能为空", trigger: "blur" }
        ],
        scode: [
          { required: true, message: "学校代码不能为空", trigger: "blur" }
        ],
        sranking: [
          { required: true, message: "院校排名不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAreaList();
  },

  mounted() {
    basearea().then(res => {
      if (res.code === 200) {
        // this.areaData = res.data
        console.log("arealist"+res.rows)
        const arealist = res.rows
        // 列表转树
        const listToTree = (list) => {
          const map = {}
          const roots = []
          let node
          let i
          for (i = 0; i < list.length; i++) {
            map[list[i].id] = i
            if (list[i].level === 1) {
              list[i].children = []
            }
          }
          for (i = 0; i < list.length; i++) {
            node = list[i]
            if (node.parentId !== 0) {
              list[map[node.parentId]].children.push(node)
            } else {
              roots.push(node)
            }
          }
          return roots
        }
        console.log(listToTree(arealist))
        this.areaData = listToTree(arealist)
      } else {
        this.$message({
          type: 'error',
          message: res.msg
        })
      }
    })// 获取地区列表

  },
  methods: {
    /** 查询学校列表列表 */
    getList()
    {
      this.loading = true;
      listSchool(this.queryParams).then(response => {
        this.schoolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    }
  ,
    /** 查询城市列表列表 */
    getAreaList()
    {
      this.loading = true;
      listArea().then(response => {
        this.AreaList = response;
        // console.log("AreaList",this.AreaList)
        console.log(JSON.stringify(response, null, 2));  // 在这里添加控制台打印语句
      });
    },

    handleProvinceChange(parentId) {
      if (!parentId) {
        // 如果 parentId 不存在或者不合法，可能需要清除市的选项或做其他处理
        this.cityOptions = [];
        return;
      }
      this.loading = true;
      getCity(parentId).then(response => {
        // 假设response是服务器返回的城市数据数组
        this.cityOptions = response;
        this.loading = false; // 加载结束
        console.log(JSON.stringify(response, null, 2));
      });
    },

    addArea(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的        {keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData)
      console.log('toData:', toData)
      console.log('obj:', obj)
    },
    removeArea(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log('fromData:', fromData)
      console.log('toData:', toData)
      console.log('obj:', obj)
    },
    selectArea() {
      this.innerVisible = true
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sid: null,
        sprovince: null,
        stypes: null,
        collegeLevel: [],
        sbatch: null,
        city: null,
        sname: null,
        scode: null,
        sranking: null,
        admissionRules: null,
        swebsite: null,
        smodel: null,
        creationYear: null,
        stuNumber: null,
        doctoralProgram: null,
        mastersProgram: null,
        sphone: null,
        recruitWeb: null,
        sdepartment: null,
        slogo: null,
        scontent: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
		admssionRule: null,
		zszc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const sid = row.sid || this.ids
	  
	  
	  
      getSchool(sid).then(response => {
        this.form = response.data;
        // 先将行数据赋值给表单变量
        // this.form = Object.assign({}, row);
        // 然后调用处理省份变化的函数，并传递省份ID初始化市级数据(解决当点击修改的时候，市没有根据省的id进行城市的初始化显示成一个id)
        this.handleProvinceChange(this.form.sprovince);
        if (this.form.collegeLevel) {
          this.form.collegeLevel = this.form.collegeLevel.split(",");
        } else {
          // 如果 collegeLevel 为 null，就给它一个默认值，比如空数组
          this.form.collegeLevel = [];
        }
        this.open = true;
        this.getAreaList()
        // this.getCity(row.parentId)
        this.getList();

        this.title = "修改学校列表";
      });
    },
    /** 学校简介 */
    handleIntroduce(row) {
      const sid = row.sid || this.ids
      getSchool(sid).then(response => {
        this.form = response.data;
        console.log(JSON.stringify(response, null, 2));  // 在这里添加控制台打印语句
        // this.open = true;
        this.title = "学校简介";
      });
    },
    /** 把省份的id传入查城市 */
    handlecity(row) {
      const scode = row.scode || this.scode
      getSchoolIntroduce(scode).then(response => {
        this.form = response;
        console.log(JSON.stringify(response, null, 2));  // 在这里添加控制台打印语句
        // this.open = true;
        this.title = "学校简介";
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.collegeLevel = this.form.collegeLevel.join(",");
          if (this.form.sid != null) {
            updateSchool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sIds = row.sid || this.ids;
      this.$modal.confirm('是否确认删除记录？').then(function() {
        return delSchool(sIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    getSchoolTypeLabel(value) {
      // 从字典中找到对应的标签
      const schoolType = this.dict.type.school_types
        .find(type => type.value === value);
      // 返回找到的标签，如果没有找到，返回一个默认字符串
      return schoolType ? schoolType.label : '未知类型';
    },
    getSchoolTypeLevel(value) {
      if (!value) {
        return '';
      }
      // 假设值是以逗号分隔的字符串，将其转换为数组
      const levelsArray = value.split(',');
      // 映射每个level到其对应的标签
      const labelsArray = levelsArray.map((level) => {
        const schoolLevel = this.dict.type.school_level
          .find(type => type.value === level.trim());
        return schoolLevel ? schoolLevel.label : '';
      });
      // 将所有标签连接成一个字符串
      return labelsArray.join('、');



    },

    handleExport() {
      this.download('school/school/export', {
        ...this.queryParams
      }, `school_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>

.form-item-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.el-form-item__content {
  padding-top: 5px; /* 减小垂直间隔 */
  padding-bottom: 5px; /* 减小垂直间隔 */
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

</style>
